﻿import SevenUPrules
import SevenUPdata
from platform.GameManager import GameManager
from platform.KA import KA, super

from platform.jutils import *
from platform.utilits import *

class SevenUPGameManager(GameManager):
	def __init__(this, bgtp_mail_):
		this.bgtp_mail = bgtp_mail_
		this.name = USR_GAMEMANAGER
		super.__init__(this)	
		this.client = false
		this.data = SevenUPdata.SevenUPdata()
		super.setState(this, GM_SETTINGS)
		GameManager.__init__(this)
	
	#add gamer
	def pre_addGamer(this, req):
		if (this.data.gamers.count(req.usr) != 0):
			return "this player here"
	
	def addGamer(this, req):
		this.data.gamers.append(req.usr)		
	
	def post_addGamer(this, req):
		this.sendRequest(req)		
	
	#remove gamer
	def pre_removeGamer(this, req):
		if (this.data.gamers.count(req.usr) == 0):
			return "no this gamer"
	
	def removeGamer(this, req):
		this.data.gamers.remove(req.usr)		
	
	def post_removeGamer(this, req):
		this.sendRequest(req)		
	
	#setGamerParty
	def pre_setGamerParty(this, req):
		if (this.data.gamers.count(req.usr) == 0):
			return "no this gamer"
		if (this.data.partyes.keys().count(req.body) == 0):
			return "no this party:" + req.body
	
	def setGamerParty(this, req):
		this.data.partyes[req.body] = req.usr
	
	def post_setGamerParty(this, req):
		this.sendRequest(req)
	
	#createAI
	def pre_createAI(this, req):
		pass
	
	def createAI(this, req):
		#def _createAI():
		#	import os; os.system('python XO\AIclient.py')
		#import thread; thread.start_new_thread(_createAI, ())		
		import os; os.startfile("XO\AIclient.py")
		
	def post_createAI(this, req):
		pass
	
	#start game
	def pre_startGame(this, req):
		if (this.data.partyes[SevenUPrules.Xchar] == null or this.data.partyes[SevenUPrules.Ochar] == null):
			return "need two players"
	
	def startGame(this, req):
		this.data.fld = SevenUPrules.createField()
		this.data.who = SevenUPrules.Xchar
		super.setState(this, GM_GAME)		
	
	def post_startGame(this, req):
		this.sendRequest(req)			
	
	#make turn
	def _isItWin(this):
		whoseWin = SevenUPrules.whoseWin(this.data.fld)
		return not (whoseWin == SevenUPrules.Fchar)
	
	def pre_makeTurn(this, req):
		if (this.data.partyes.get(this.data.who) != req.usr):
			return "it is not your turn"
		if (this._isItWin()):
			return "the game is over"
		if (not SevenUPrules.isItTurn(this.data.fld, req.body[0], req.body[1], this.data.who)):
			return "it is not avalibale turn"
	
	def makeTurn(this, req):
		SevenUPrules.makeTurn(this.data.fld, req.body[0], req.body[1])
		if this._isItWin():
			this.stopGame()			
		else:
			if this.data.who == SevenUPrules.Xchar:
				who_ = SevenUPrules.Ochar
			else:	
				who_ = SevenUPrules.Xchar
			
			if (SevenUPrules.canMakeTurn(this.data.fld, who_)):
				this.data.who = who_
	
	def post_makeTurn(this, req):
		this.sendRequest(req)		
		

